package common

import (
	"bw-renting/model/mysql"
	"fmt"
	"github.com/smartwalle/alipay/v3"
	"github.com/zeromicro/go-zero/core/logx"
	"log"
)

// 简单工厂模式

// PayMent 支付入口接口
type PayMent interface {
	Payment(pay mysql.HouseOrder) (string, error)
}

// Alipay 支付宝结构体
type Alipay struct {
	AppId      string
	PrivateKey string
	PublicKey  string
}

// WechatPay 微信结构体
type WechatPay struct {
}

var ali Alipay
var Client *alipay.Client

func init() {
	ali.AppId = "9021000131608698"
	ali.PrivateKey = "MIIEowIBAAKCAQEAzQNX1iaFKUysPfOkKY5VD6y8LPmFb5r4l/PLyivQkf5V2BQ9IhlAPUKRTVocM3Y1YyqftfAlrlsXYuErNfoRS109oylNn9uApVegeXZ9pCF/mOyxUZlr3jnCQWJZdM9sCA4J5rCxpiDb3PSAMrlRFUJcaqBMZ7lx6Ua7npMhpfy3SZaGVL3X1BYsJ7tjmdEAcHSga8/lFZfuQLkuIQAIkyTgqUU1uj1r4Iatc7xqO3+FUTxySXCixFIygV4WwlszBcjmrohYKoW72i94MpRRKE1pzl3Swb9DZYiPZDqvN8zfCTCJdWaO6z40/xVNRIgycWg33QlzMvhx+aF9Gn9uPwIDAQABAoIBAQCWQ2QG93bUfXklc0WYm9UmxwGpqT2vPpQEs9FjnleiGhuLY9InAwD9paPgYTKYWYTp6VzkOl8z+1oZxFYqmt5AMdgyldxqVbVl+uMJA9s1CMSALsQMvfm9CPKjf9V3c2yIPtns9wdOb3kW6zJne0K95UTddh5qTBb81zY/FTIteMxafKG1LlxaWWBnwexZfLbVq7/+91d4bQjr+//cB2Qder8d3BOe0vlgzmVQVLUNB8/1aCzFj5YZti4bTIymGg/Onfh3ReTBzOKVg4tOzAZ4np+WvLQroadl+/EKLEYXDA/vEeNge7Q6Iv4Va9HQ3PxOM8ti5ZuvCq7X4q3D26gJAoGBAOvOXcOinmLnWZYLl6Apy1n4Fn5TsbTKlpkyv3uLzt2g/94QcfDb9lLih5X9eoOoxCfylAemoz2fMuJ4lLad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lubZLPU1tvmxtADUg0MWlDLJ6hDL1Is9YISFIyRAECQCb4wyL048pluvm2yJbd5XQFTL+QAar6g2RCnXvNNX7qP2dkqXSfFyzhCDwNZLbNQIDAQAB"
	var err error
	Client, err = alipay.New(ali.AppId, ali.PrivateKey, false)
	if err != nil {
		log.Println(err)
		log.Println("初始化alipay")
		return
	}
	err = Client.LoadAliPayPublicKey(ali.PublicKey)
	if err != nil {
		log.Println(err)
		return
	}
}

// Payment 支付宝支付入口
func (al *Alipay) Payment(order mysql.HouseOrder) (payurl string, err error) {
	logx.Debug(order)
	var p = alipay.TradeWapPay{}
	p.NotifyURL = "http://7a9a733c.r7.vip.cpolar.cn/api/PayNotify" //异步回调
	p.ReturnURL = "http://7a9a733c.r7.vip.cpolar.cn/api/PayReturn" //同步
	p.Subject = order.Title                                        //标题
	p.OutTradeNo = order.OrderSn                                   //唯一单号
	p.TotalAmount = fmt.Sprint(order.Price)                        //价格
	p.ProductCode = "QUICK_WAP_WAY"

	url, err := Client.TradeWapPay(p)
	if err != nil {
		log.Println(err)
		return "", err
	}
	// 这个 payURL 即是用于打开支付宝支付页面的 URL，可将输出的内容复制，到浏览器中访问该 URL 即可打开支付页面。
	payurl = url.String()
	log.Println("返回url")
	return payurl, nil
}
